#define I2C_H
#include "I2C.h"
#include "../iodefine.h"

static unsigned char sub_SDA_Read( void );

static void sub_SDA_DirectSet( unsigned char u8_Tmp );
static void sub_SCL_DirectSet( unsigned char u8_Tmp );
static void sub_SDA_Set( unsigned char u8_Tmp );
static void sub_SCL_Set( unsigned char u8_Tmp );

void I2C_Init( void )
{
  sub_SDA_DirectSet( _OUTPUT );
  sub_SCL_DirectSet( _OUTPUT );
  sub_SCL_Set( _HIGH );
  I2C_Flash();
  sub_SDA_Set( _HIGH );
  I2C_Flash();
}

void I2C_Flash( void )
{
  unsigned char i;
  
  for( i=0; i<8; i++ )
  {}
}

void I2C_Delay( unsigned int u16_Tmp )
{
  unsigned int i;
  
  for( i=0; i<u16_Tmp; i++ )
  {}
}



void I2C_Start( void )
{
  sub_SDA_DirectSet( _OUTPUT );
  sub_SDA_Set( _HIGH );
  I2C_Flash();
  sub_SCL_Set( _HIGH );
  I2C_Flash();
  sub_SDA_Set( _LOW );
  I2C_Flash();
  sub_SCL_Set( _LOW );
  I2C_Flash();
}

void I2C_Stop( void )
{
  sub_SDA_DirectSet( _OUTPUT );
  sub_SDA_Set( _LOW );
  I2C_Flash();
  sub_SCL_Set( _HIGH );
  I2C_Flash();
  sub_SDA_Set( _HIGH );
  I2C_Flash();
}

void I2C_WriteX( unsigned char u8_Tmp )
{
  unsigned char i,j;
  
  sub_SDA_DirectSet( _OUTPUT );
  for( i=0; i<8; i++ )
  {
    j = (u8_Tmp>>(7-i)) & 0x01;
    sub_SCL_Set( _LOW );
    I2C_Flash();
    if( 1 == j )
    {
      sub_SDA_Set( _HIGH );
    }
    else
    {
      sub_SDA_Set( _LOW );
    }
    I2C_Flash();
    sub_SCL_Set( _HIGH );
    I2C_Flash();
  }
  sub_SCL_Set( _LOW );
  I2C_Flash();
  sub_SDA_Set( _HIGH );
  I2C_Flash();
}

unsigned char I2C_ReadX( void )
{
  unsigned char i,j,k;
  unsigned char u8_Tmp;
  
  sub_SCL_Set( _LOW );
  I2C_Flash();
  sub_SDA_Set( _HIGH );
  sub_SDA_DirectSet( _INPUT );
  
  k = 0;
  for( i=0;i<8;i++ )
  {
    I2C_Flash();
    sub_SCL_Set( _HIGH );
    I2C_Flash();
    u8_Tmp = sub_SDA_Read();
    if( 1 == u8_Tmp )
    {
      j = 1;
    }
    else
    {
      j = 0;
    }
        
    k = (k<<1)|j;
    sub_SCL_Set( _LOW );
  }
  I2C_Flash();
  
  return k ;
}

unsigned char I2C_ACK( void )
{
  unsigned char u8_Tmp,i=0;
  
  sub_SDA_DirectSet( _INPUT );
  sub_SCL_Set( _HIGH );
  I2C_Flash();
  u8_Tmp = sub_SDA_Read();
  while( (1==u8_Tmp)&&(i<11) )
  {
    i++;
  }
  sub_SCL_Set( _LOW );
  I2C_Flash();
  
  if( i > 9 )
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

void sub_SDA_DirectSet( unsigned char u8_Tmp )
{
  DDR_EESDA = u8_Tmp;
}

void sub_SCL_DirectSet( unsigned char u8_Tmp )
{
  DDR_EESCL = u8_Tmp;
}

void sub_SDA_Set( unsigned char u8_Tmp )
{
 IO_EESDAO = u8_Tmp;
}

void sub_SCL_Set( unsigned char u8_Tmp )
{
  IO_EESCL = u8_Tmp;
}

unsigned char sub_SDA_Read( void )
{
  unsigned char u8_Tmp;
  
  u8_Tmp = IO_EESDAI;
  
  return u8_Tmp;
}
